package com.gframework.core.service.lock;

import java.util.concurrent.TimeUnit;

import org.redisson.api.RedissonClient;
import org.slf4j.LoggerFactory;

/**
 * 基于redis的分布式锁实现类.
 * 
 * @since 1.0.0
 * @author Ghwolf
 */
public class RedisDistributedLock implements DistributedLock {

	/**
	 * redis增强操作对象
	 */
	private RedissonClient redisson;

	public RedisDistributedLock(RedissonClient redisson) {
		this.redisson = redisson;
		LoggerFactory.getLogger(RedisDistributedLock.class).info("====> 已启用 RedisDistributedLock 分布式锁！");
	}

	@Override
	public void lock(String distributedKey, long leaseTime, TimeUnit unit) {
		this.redisson.getLock(distributedKey).lock(leaseTime, unit);
	}

	@Override
	public boolean unlock(String distributedKey) {
		return this.redisson.getLock(distributedKey).forceUnlock();
	}

	@Override
	public boolean tryLock(String distributedKey, long leaseTime, TimeUnit unit) {
		try {
			return this.tryLock(distributedKey, 0, leaseTime, unit);
		} catch (InterruptedException e) {
			return false;
		}
	}

	@Override
	public boolean tryLock(String distributedKey, long waitTimeout, long leaseTime, TimeUnit unit) throws InterruptedException {
		return this.redisson.getLock(distributedKey).tryLock(waitTimeout, leaseTime, unit);
	}

	@Override
	public boolean isLock(String distributedKey) {
		return this.redisson.getLock(distributedKey).isLocked();
	}

}
